﻿#include "TcpServeManager.h"

TcpServeManager::TcpServeManager()
{
    //连接
    connect(&mTcpServer, &QTcpServer::newConnection, this, &TcpServeManager::newConnectSlot);
    openListen();
}

void TcpServeManager::openListen()
{
    qDebug() << "open Listen";
    mTcpServer.listen(QHostAddress::Any, 9528);
    set_listenFlag(true);
}

void TcpServeManager::closeListen()
{
    qDebug() << "close listen";
    mTcpServer.close();
    set_listenFlag(false);
    for(int i=0;i<mClientVec.size();i++){
        mClientVec[i]->disconnectServer();
    }
}

void TcpServeManager::newConnectSlot() {
    TestLog("have new connect");
    //程序到此步骤证明有用户链接，启用socket通信传输并解析数据
    //实例此次通信对象  nextPendingConnection得到一个可供通信的套接字对象
    QTcpSocket* client = mTcpServer.nextPendingConnection();
    NewTcpClient::ptr nT = std::make_shared<NewTcpClient>();
    nT->setClientSocket(client);
    mClientVec.push_back(nT);
}

NewTcpClient *TcpServeManager::getClientPtr(const QString& account)
{
    for(int i =  mClientVec.size() -1; i >= 0; i--) {
        NewTcpClient::ptr it = mClientVec[i];
        //如果连接无效 就把指针删除掉
        if(!it->getTcpSocket()->isValid()) {
            mClientVec.remove(i);
            continue;
        }
        qDebug() << "it account = " << it->getAccount();
        if(it->getAccount() == account) {
            return it.get();
        }
    }
    return nullptr;
}


